#!/usr/bin/env python
# -*- coding:utf-8 -*-
from datetime import datetime

from conn.MyLogs import MyLogs
from members.beans.MemberAddressObj import MemberAddressObj


class MemberAddressService:
    conn = None

    def __init__(self, conn):
        self.conn = conn

    def fetch(self, param):
        try:
            count_sql = f" SELECT count(`member_id`) FROM `view_member_address` WHERE 1=1 %s"
            fetch_sql = f" SELECT `id`,`member_id`,`address_json`,`name`,`uname`,`sex`,`STATUS` " \
                        f" FROM `view_member_address` WHERE 1=1 %s "
            where_sql = ""
            if len(param['key']) > 0:
                where_sql = where_sql + f" AND CONCAT(`member_id`,`uname`,`name`) like CONCAT('%',\'{param['key']}\','%') "
            int_begin = 0
            if int(param['pageNum']) > 1:
                int_begin = (int(param['pageNum']) - 1) * int(param['pageSize'])
            elif int(param['pageNum']) == 1:
                int_begin = 0 * int(param['pageSize'])
            where_sql_no_limit = where_sql
            where_sql_limit = where_sql_no_limit + f" LIMIT {int_begin}, {int(param['pageSize'])}"
            data_total = self.conn.sql_fetch(count_sql % where_sql_no_limit)
            data_list = self.conn.sql_fetch(fetch_sql % where_sql_limit)
            items = []
            if len(data_list) > 0:
                items = [MemberAddressObj.load_db_2_dict(data=item) for item in data_list]
            return {"code": 200, "data": items, "total": data_total[0][0]}
        except Exception as e:
            MyLogs.logger.error("ERROR: %s" % e)
        return {"code": 500, "data": None}

    def fetch_one(self, memberId):
        fetch_sql = f" SELECT `id`,`member_id`,`member_sno`,`address_json`,`name`,`uname`,`sex`,`STATUS`" \
                    f" FROM `view_member_address` as `view_member_address` WHERE 1=1 " \
                    f" AND `member_id` = \'{memberId}\'"
        try:
            items = self.conn.sql_fetch(fetch_sql)
            if len(items) > 0:
                res = [MemberAddressObj.load_db_2_dict(item) for item in items][0]
                return {"code": 200, "data": res}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    def add_address(self, address: object, member_id: str):
        try:
            add_check = self.count_one(member_id=member_id)
            if not add_check:
                execute_SQL = f" INSERT INTO `mem_member_address` ({MemberAddressObj.to_string(False)}) VALUES( %s )"
                execute_SQL = execute_SQL % MemberAddressObj.concat_datas(address)
            else:
                str_val = MemberAddressObj.makeAddr(address)
                execute_SQL = f" UPDATE `mem_member_address` SET `address_json`= '%s' WHERE `member_id` = \'{member_id}\'"
                execute_SQL = execute_SQL % str_val
            self.conn.sql_commit(execute_SQL)
            return {"code": 200, "data": None}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    def update_address(self, address: object, member_id):
        # 获取当前时间
        current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        try:
            add_check = self.count_one(member_id=member_id)
            if not add_check:
                return {"code": 404, "data": None}
            str_val = MemberAddressObj.makeAddr(address)
            execute_SQL = f" UPDATE `mem_member_address` SET `address_json`= '%s' WHERE `member_id` = \'{member_id}\'"
            execute_SQL = execute_SQL % str_val
            self.conn.sql_commit(execute_SQL)
            return {"code": 200, "data": None}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    def drop_address(self, address: object, member_id):
        # 获取当前时间
        current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        add_check = self.count_one(member_id=member_id)
        if not add_check:
            return {"code": 404, "data": None}
        str_val = MemberAddressObj.makeAddr(address)
        execute_SQL = f" UPDATE `mem_member_address` SET `address_json`= '%s' WHERE `member_id` = \'{member_id}\'"
        execute_SQL = execute_SQL % str_val
        self.conn.sql_commit(execute_SQL)
        return {"code": 200, "data": None}

    def res_address(self, address: object, member_id):
        # 获取当前时间
        current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        add_check = self.count_one(member_id=member_id)
        if not add_check:
            return {"code": 404, "data": None}
        str_val = MemberAddressObj.makeAddr(address)
        execute_SQL = f" UPDATE `mem_member_address` SET `address_json`= '%s' WHERE `member_id` = \'{member_id}\'"
        execute_SQL = execute_SQL % str_val
        self.conn.sql_commit(execute_SQL)
        return {"code": 200, "data": None}

    def count_one(self, member_id) -> bool:
        fetch_sql = f"SELECT count(`MEMBER_ID`) FROM `mem_member_address` WHERE 1 = 1 " \
                    f" AND `MEMBER_ID` = \'{member_id}\'"
        try:
            items = self.conn.sql_fetch(fetch_sql)
            if len(items) > 0:
                return items[0][0] > 0
            return False
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}
